package com.ns.dcjh.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.bumptech.glide.util.Util;
import com.ns.dcjh.MyApplication;
import com.ns.dcjh.R;
import com.ns.dcjh.constant.Constant;
import com.ns.dcjh.listener.MyUMShareListener;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMMin;
import com.umeng.socialize.media.UMWeb;

import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class ShareUtils {

    //分享微信图片
    public static void shareWxImageWithBitmap(Context context, SHARE_MEDIA platform, byte[] image) {
        if (image == null) {
            Log.d("shareWxImage","获取图片失败，请重试");
            ToastUtils.info(context, "获取图片失败，请重试");
        }

        IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, Constant.WECHAT_APP_ID);
        iwxapi.registerApp(Constant.WECHAT_APP_ID);
        if (!iwxapi.isWXAppInstalled()) {
            ToastUtils.info(context, "您的手机没有安装微信");
            Log.d("shareWxImage","您的手机没有安装微信");
            return;
        }
        Log.d("shareWxImage","开始构建微信Image对象");
        WXImageObject imageObject = new WXImageObject(image);
        Log.d("shareWxImage","开始构建微信传输对象");
        WXMediaMessage mediaMessage = new WXMediaMessage();
        mediaMessage.mediaObject = imageObject;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = mediaMessage;
        req.transaction = buildTransaction("wximage");
        if (platform == SHARE_MEDIA.WEIXIN) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        Log.d("shareWxImage","微信对象构建成功，开始发送");
        iwxapi.sendReq(req);
        Log.d("shareWxImage","微信对象发送成功");

//        BitmapUtils.bitmapSaveFileToStorage(image).subscribe(new Observer<File>() {
//            @Override
//            public void onSubscribe(@NonNull Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(@NonNull File file) {
//                String imagePath = file.getAbsolutePath();
//
//                //Android 11以上必须以fileprovider分享
//                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
//                    Uri contentUri = FileProvider.getUriForFile(context, "com.ns.dcjh.fileprovider", file);
//                    // 授权给微信访问路径
//                    context.grantUriPermission("com.tencent.mm", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
//
//                    imagePath = contentUri.toString();
//                }
////                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
////                if (BitmapUtils.isNeedCompress(bitmap)) {
////                    byte[] bitmapByte = BitmapUtils.bitmap2Bytes(bitmap);
////                    bitmap = BitmapUtils.byte2Bitmap(bitmapByte);
////                }
//
//                WXImageObject imageObject = new WXImageObject();
//                imageObject.imagePath = imagePath;
//                WXMediaMessage mediaMessage = new WXMediaMessage();
//                mediaMessage.mediaObject = imageObject;
//
//                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                req.message = mediaMessage;
//                req.transaction = buildTransaction("wximage");
//                if (platform == SHARE_MEDIA.WEIXIN) {
//                    req.scene = SendMessageToWX.Req.WXSceneSession;
//                } else {
//                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
//                }
//                iwxapi.sendReq(req);
//
//                MyApplication.getInstance().getWxShareImageList().add(file.getAbsolutePath());
//            }
//
//            @Override
//            public void onError(@NonNull Throwable e) {
//
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
    }

    //分享微信图片
    public static void shareWxImageWithBitmapByUmeng(Context context, SHARE_MEDIA platform, Bitmap image, MyUMShareListener umShareListener) {
        if (image == null) {
            ToastUtils.info(context, "获取图片失败，请重试");
        }

        UMImage umImage;
        if (image == null) {
            umImage = new UMImage(context, R.mipmap.ic_logo_1);
        } else {
            umImage = new UMImage(context, image);
        }
        umImage.compressStyle =UMImage.CompressStyle.QUALITY;

        new ShareAction((Activity) context)
                .setPlatform(platform)
                .withMedia(umImage)
                .setCallback(umShareListener)
                .share();

    }

    /**
     * 分享微信链接
     * @param context
     * @param platform
     * @param title
     * @param description
     * @param url
     * @param image
     * @param umShareListener
     */
    public static void shareWxLink(Context context,
                                   SHARE_MEDIA platform,
                                   String title,
                                   String description,
                                   String url,
                                   Bitmap image,
                                   MyUMShareListener umShareListener) {

        UMImage umImage;
        if (image == null) {
            umImage = new UMImage(context, R.mipmap.ic_logo_1);
        } else {
            umImage = new UMImage(context, image);
            ToastUtils.info(context, "拿到分享缩略图大小为"+image.getByteCount());
        }
        UMWeb umWeb = new UMWeb(url);
        umWeb.setTitle(title);
        umWeb.setDescription(description);
        umWeb.setThumb(umImage);
        ToastUtils.info(context, "1");
        new ShareAction((Activity) context)
                .setPlatform(platform)
                .withMedia(umWeb)
                .setCallback(umShareListener)
                .share();
    }

    /**
     * 分享微信小程序
     * @param context
     * @param platform
     * @param title
     * @param userName
     * @param link
     * @param image
     * @param umShareListener
     */
    public static void shareWxMp(Context context,
                                 SHARE_MEDIA platform,
                                 String title,
                                 String userName,
                                 String link,
                                 Bitmap image,
                                 MyUMShareListener umShareListener) {

        ToastUtils.info(context, "分享好友小程序");
        shareMiniProgram(context, title, userName, link, image);

//        UMImage umImage;
//        if (image == null) {
//            umImage = new UMImage(context, R.mipmap.ic_logo_1);
//        } else {
//            umImage = new UMImage(context, image);
//            ToastUtils.info(context, "拿到分享缩略图大小为"+image.getByteCount());
//        }
//
//        UMMin umMin = new UMMin(Constant.WECHAT_MP_URL);
//        umMin.setThumb(umImage);
//        umMin.setTitle(title);
//        umMin.setDescription(title);
//        umMin.setPath(link);
//        if (StringUtils.isEmpty(userName)) {
//            umMin.setUserName(Constant.WECHAT_MP_ID);
//        } else {
//            umMin.setUserName(userName);
//        }
//
//        ToastUtils.info(context, "1");
//        new ShareAction((Activity) context)
//                .withMedia(umMin)
//                .setPlatform(platform)
//                .setCallback(umShareListener)
//                .share();

    }

    private static String buildTransaction(String type) {
        if (type == null) {
            return String.valueOf(System.currentTimeMillis());
        } else {
            return type + System.currentTimeMillis();
        }
    }

    public static void shareMiniProgram(Context context,
                                        String title,
                                        String userName,
                                        String link,
                                        Bitmap image) {

        ToastUtils.info(context, "分享好友小程序");
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, Constant.WECHAT_APP_ID, true);
        iwxapi.registerApp(Constant.WECHAT_APP_ID);
        if (!iwxapi.isWXAppInstalled()) {
            ToastUtils.info(context, "您的手机没有安装微信");
            return;
        }

        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = Constant.WECHAT_MP_URL; // 兼容低版本的网页链接
        miniProgramObj.miniprogramType = 0;
        // 小程序原始id
        if (StringUtils.isEmpty(userName)) {
            miniProgramObj.userName = Constant.WECHAT_MP_ID;
        } else {
            miniProgramObj.userName = userName;
        }
        miniProgramObj.path = link;            //小程序页面路径
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = title;                    // 小程序消息title
        msg.description = title;               // 小程序消息desc

        msg.thumbData = getWXThumb(image, 500).toByteArray();
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
        iwxapi.sendReq(req);
    }

    public static void shareWeb(Context context,
                                boolean isFriend,
                                String title,
                                String description,
                                String webUrl,
                                Bitmap bitmap) {
        ToastUtils.info(context, "分享朋友圈");
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, Constant.WECHAT_APP_ID, true);
        iwxapi.registerApp(Constant.WECHAT_APP_ID);
        if (!iwxapi.isWXAppInstalled()) {
            ToastUtils.info(context, "您的手机没有安装微信");
            return;
        }
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = webUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = description;
        msg.thumbData = getWXThumb(bitmap, 100).toByteArray();
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        //WXSceneTimeline朋友圈    WXSceneSession聊天界面
        req.scene = isFriend ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        req.message = msg;
        req.transaction = String.valueOf(System.currentTimeMillis());
        iwxapi.sendReq(req);
    }

    public static final int IMAGE_LENGTH_LIMIT = 6291456;
    private static ByteArrayOutputStream getWXThumb(Bitmap resource, int dstSize) {
        if (resource == null || resource.isRecycled()) {
            throw new IllegalStateException("不能使用已回收或空的Bitmap");
        }
        Bitmap thumb = Bitmap.createScaledBitmap(resource, dstSize, dstSize, true);
        if (thumb == null || thumb.isRecycled()) {
            throw new IllegalStateException("不能使用已回收或空的缩略图Bitmap");
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int quality = 90;
        int realLength = Util.getBitmapByteSize(resource.getWidth(), resource.getHeight(), Bitmap.Config.RGB_565);
        if (realLength > IMAGE_LENGTH_LIMIT) {
            quality = (int) (IMAGE_LENGTH_LIMIT * 1f / realLength * 100);
        }
        if (quality < 75) {
            quality = 75;
        }
        resource.compress(Bitmap.CompressFormat.JPEG, quality, output);
        output.reset();
        thumb.compress(Bitmap.CompressFormat.JPEG, 85, output);
//        resource.recycle();
        // 如果这一点之后不再需要thumb bitmap，请确保回收
//        thumb.recycle();
        return output;
    }

}
